﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac.Integration.Web;
using Autofac.Integration.Web.Mvc;
using FluentValidation.Mvc;
using GiveAQuiz.Web.Validation;
using GiveAQuizSite.Services;
using GiveAQuiz.Web.Logging;
using System;

namespace GiveAQuizSite
{
  public class MvcApplication : HttpApplication, IContainerProviderAccessor
  {
    static IContainerProvider _containerProvider;

    public IContainerProvider ContainerProvider
    {
      get { return _containerProvider; }
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

      routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");

      routes.MapRoute(
          "Default",                                              // Route name
          "{controller}/{action}/{id}",                           // URL with parameters
          new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
      );

    }

    protected void Application_Start()
    {
      // Register the routes as normal
      RegisterRoutes(RouteTable.Routes);
      InitializeContainer();
    }

    private void InitializeContainer()
    {
      var container = Bootstraper.InitializeContainer();     

      _containerProvider = new ContainerProvider(container);

      ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(ContainerProvider));

      // create factory using Autofac to resolve validation types
      var factory = new AutofacValidatorFactory(container);

      // Tell MVC to use FluentValidation library for validation
      ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(factory));
      DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

    }

    // Log the errors that occur
    void Application_Error(object sender, EventArgs e)
    {
      //get reference to the source of the exception chain
      Exception ex = Server.GetLastError().GetBaseException();
      Logger.LogException("Server Error Occurred", ex);
    }
  }
}